<?php

/**
 * Name: 审核控制器
 * User: Silent
 * Date: 2025-11-07
 * Time: 16:30:00
 */

namespace App\Http\Controllers\V1\Resources\Checkin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Checkin\ReviewRequest;
use App\Services\Checkin\ReviewService;
use Illuminate\Http\Request;
use Exception;

class ReviewController extends Controller
{
    protected $reviewService;

    public function __construct(ReviewService $reviewService)
    {
        $this->reviewService = $reviewService;
    }

    /**
     * 班长提交审核
     * POST /api/v1/review/leader/submit
     */
    public function leaderSubmit(ReviewRequest $request)
    {
        try {
            $employee = $request->input('current_user');
            $reviewData = $request->validated();
            $date = $request->input('date', today()->format('Y-m-d'));

            // 验证是否为班长
            if (!$this->isLeader($employee)) {
                return $this->_error('您没有权限进行班长审核');
            }

            $result = $this->reviewService->submitLeaderReview($employee, $reviewData, $date);

            if ($result['success']) {
                return $this->_success($result['message'], $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('提交审核失败：' . $e->getMessage());
        }
    }

    /**
     * 主管提交审核
     * POST /api/v1/review/supervisor/submit
     */
    public function supervisorSubmit(ReviewRequest $request)
    {
        try {
            $employee = $request->input('current_user');
            $reviewData = $request->validated();
            // $teamName = $request->input('team_name');
            $date = $request->input('date', today()->format('Y-m-d'));

            // 验证是否为主管
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限进行主管审核');
            }

            // if (empty($teamName)) {
            //     return $this->_error('班组名称不能为空');
            // }

            // // 支持多个班组（逗号分隔）
            // $teamNames = array_filter(array_map('trim', explode(',', $teamName)));

            // if (empty($teamNames)) {
            //     return $this->_error('班组名称不能为空');
            // }

            // $results = [];
            // $errors = [];

            // foreach ($teamNames as $teamName) {
            //     $result = $this->reviewService->submitSupervisorReview($employee, $teamName, $reviewData, $date);

            //     if ($result['success']) {
            //         $results[] = $result['data'];
            //     } else {
            //         $errors[] = "班组 {$teamName}: {$result['message']}";
            //     }
            // }

            // if (!empty($errors)) {
            //     return $this->_error(implode('; ', $errors));
            // }

            // return $this->_success('审核提交成功', $results);

            $result = $this->reviewService->submitSupervisorReview($employee, $reviewData, $date);

            if ($result['success']) {
                return $this->_success($result['message'], $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('提交审核失败：' . $e->getMessage());
        }
    }

    /**
     * 检查班长当日审核状态
     * GET /api/v1/review/leader/status
     */
    public function leaderStatus(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $date = $request->input('date', today()->format('Y-m-d'));

            // 验证是否为班长
            if (!$this->isLeader($employee)) {
                return $this->_error('您没有权限查看班长审核状态');
            }

            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                return $this->_error('无效的日期格式');
            }

            $result = $this->reviewService->checkLeaderReviewStatus($employee, $date);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取审核状态失败：' . $e->getMessage());
        }
    }

    /**
     * 检查主管当日审核状态
     * GET /api/v1/review/supervisor/status
     */
    public function supervisorStatus(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $date = $request->input('date', today()->format('Y-m-d'));

            // 验证是否为主管
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限查看主管审核状态');
            }

            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                return $this->_error('无效的日期格式');
            }

            $result = $this->reviewService->checkSupervisorReviewStatus($employee, $date);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取审核状态失败：' . $e->getMessage());
        }
    }

    /**
     * 获取班长待审核数据
     * GET /api/v1/review/leader/pending
     */
    public function leaderPending(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $date = $request->input('date', today()->format('Y-m-d'));

            // 验证是否为班长
            if (!$this->isLeader($employee)) {
                return $this->_error('您没有权限查看班长审核数据');
            }

            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                return $this->_error('无效的日期格式');
            }

            $result = $this->reviewService->getLeaderPendingReview($employee, $date);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取审核数据失败：' . $e->getMessage());
        }
    }

    /**
     * 获取主管待审核数据
     * GET /api/v1/review/supervisor/pending
     */
    public function supervisorPending(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $date = $request->input('date', today()->format('Y-m-d'));

            // 验证是否为主管
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限查看主管审核数据');
            }

            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                return $this->_error('无效的日期格式');
            }

            $result = $this->reviewService->getSupervisorPendingReview($employee, $date);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取审核数据失败：' . $e->getMessage());
        }
    }

    /**
     * 获取主管视图：班组状态和组员打卡明细
     * GET /api/v1/review/supervisor/teams-view
     */
    public function supervisorTeamsView(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $date = $request->input('date', today()->format('Y-m-d'));

            // 验证是否为主管/部长/副部长
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限查看班组详情');
            }

            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                return $this->_error('无效的日期格式');
            }

            $result = $this->reviewService->getSupervisorTeamsView($employee, $date);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取班组详情失败：' . $e->getMessage());
        }
    }

    /**
     * 获取审核详情
     * GET /api/v1/review/detail/{date}/{team}
     */
    public function detail(Request $request, $date, $team)
    {
        try {
            $employee = $request->input('current_user');

            // 验证日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                return $this->_error('无效的日期格式');
            }

            // 获取用户角色
            $userRole = $this->getUserRole($employee);

            // 权限检查
            if ($userRole === 'employee') {
                return $this->_error('您没有权限查看审核详情');
            }

            if ($userRole === 'leader' && $employee->team !== $team) {
                return $this->_error('您只能查看本班组的审核详情');
            }

            $result = $this->reviewService->getReviewDetail($team, $date, $userRole);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取审核详情失败：' . $e->getMessage());
        }
    }

    /**
     * 获取审核记录列表
     * GET /api/v1/review/records
     */
    public function records(Request $request)
    {
        try {
            $employee = $request->input('current_user');
            $type = $request->input('type', 'leader'); // leader 或 supervisor
            $perPage = $request->input('per_page', 15);

            // 权限检查
            if ($type === 'leader' && !$this->isLeader($employee)) {
                return $this->_error('您没有权限查看班长审核记录');
            }

            if ($type === 'supervisor' && !$this->isSupervisor($employee)) {
                return $this->_error('您没有权限查看主管审核记录');
            }

            $filters = $this->buildFilters($request);
            $result = $this->reviewService->getReviewRecords($employee, $type, $perPage, $filters);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取审核记录失败：' . $e->getMessage());
        }
    }

    /**
     * 获取审核统计
     * GET /api/v1/review/statistics
     */
    public function statistics(Request $request)
    {
        try {
            $employee = $request->input('current_user');

            // 只有主管可以查看统计
            if (!$this->isSupervisor($employee)) {
                return $this->_error('您没有权限查看审核统计');
            }

            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $result = $this->reviewService->getAbnormalReviewStatistics($startDate, $endDate);

            if ($result['success']) {
                return $this->_success('获取成功', $result['data']);
            } else {
                return $this->_error($result['message']);
            }

        } catch (Exception $e) {
            return $this->_error('获取统计失败：' . $e->getMessage());
        }
    }

    /**
     * 检查是否为班长
     * 注意：副班长不属于班长权限，只有班长、组长才有 leader 权限
     */
    private function isLeader($employee)
    {
        $position = $employee->position;
        return in_array($position, ['班长', '组长']);
    }

    /**
     * 检查是否为主管
     */
    private function isSupervisor($employee)
    {
        $position = $employee->position;
        return in_array($position, ['主管', '部长', '经理', '副主管', '副部长']);
    }

    /**
     * 获取用户角色
     */
    private function getUserRole($employee)
    {
        if ($this->isSupervisor($employee)) {
            return 'supervisor';
        } elseif ($this->isLeader($employee)) {
            return 'leader';
        } else {
            return 'employee';
        }
    }

    /**
     * 构建筛选条件
     */
    private function buildFilters($request)
    {
        $filters = [];

        if ($request->has('start_date')) {
            $filters['start_date'] = $request->input('start_date');
        }

        if ($request->has('end_date')) {
            $filters['end_date'] = $request->input('end_date');
        }

        if ($request->has('status')) {
            $filters['status'] = $request->input('status');
        }

        if ($request->has('team_name')) {
            $filters['team_name'] = $request->input('team_name');
        }

        return $filters;
    }
}

